<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生信息管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
    <style>
        body {
            padding: 2rem;
            background-color: #f8f9fa;
        }
        .table-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 30px;
        }
        .table td, .table th {
            vertical-align: middle;
            text-align: center;
        }
        .action-buttons {
            min-width: 120px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
        }
        .search-box {
            max-width: 300px;
        }
        .global-actions {
            margin-bottom: 20px;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        .search-results-info {
            margin-bottom: 15px;
            color: #6c757d;
        }
        .pagination-container {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h2><i class="bi bi-people-fill"></i> 学生信息管理系统</h2>
        <div class="search-box">
            <div class="input-group">
                <input type="text" id="search-input" class="form-control" placeholder="搜索学生..." value="">
                <button class="btn btn-outline-secondary" type="button" onclick="searchStudents()">
                    <i class="bi bi-search"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- 搜索结果信息 -->
    <div class="search-results-info" id="search-results-info"></div>

    <!-- 全局操作按钮 -->
    <div class="global-actions">
        <div class="d-flex align-items-center">
            <label for="items-per-page" class="me-2">每页显示:</label>
            <select id="items-per-page" class="form-select form-select-sm" style="width: 80px;" onchange="changeItemsPerPage()">
                <option value="5" selected>5</option>
                <option value="10">10</option>
                <option value="20">20</option>
            </select>
        </div>
        <button class="btn btn-primary" onclick="openAddModal()">
            <i class="bi bi-plus-circle"></i> 增加
        </button>
        <button class="btn btn-danger" onclick="deleteSelectedStudents()">
            <i class="bi bi-trash"></i> 删除
        </button>
        <button class="btn btn-warning" onclick="editSelectedStudent()">
            <i class="bi bi-pencil"></i> 修改
        </button>
    </div>

    <!-- 学生表格 -->
    <div class="table-container">
        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead class="table-light">
                <tr>
                    <th width="5%"><input type="checkbox" id="select-all"></th>
                    <th width="10%">学号</th>
                    <th width="25%">姓名</th>
                    <th width="15%">性别</th>
                    <th width="15%">生日</th>
                    <th width="20%">操作</th>
                </tr>
                </thead>
                <tbody id="student-table-body">
                <!-- 学生数据动态插入 -->
                <tr>
                    <td colspan="6" class="text-center">加载中...</td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-container">
        <nav aria-label="Page navigation">
            <ul class="pagination" id="pagination">
                <!-- 分页按钮将动态生成 -->
            </ul>
        </nav>
    </div>
</div>

<!-- 添加/编辑学生模态框 -->
<div class="modal fade" id="student-modal" tabindex="-1" aria-labelledby="student-modal-label" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="student-modal-label"><i class="bi bi-person-plus"></i> 添加学生</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="student-form">
                    <input type="hidden" id="studentId">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="name" class="form-label">姓名</label>
                            <input type="text" class="form-control" id="name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="gender" class="form-label">性别</label>
                            <select class="form-select" id="gender" required>
                                <option value="">请选择</option>
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                        <div class="col-md-12 mb-3">
                            <label for="birthday" class="form-label">生日</label>
                            <input type="date" class="form-control" id="birthday" required>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                    <i class="bi bi-x-circle"></i> 取消
                </button>
                <button type="button" class="btn btn-primary" onclick="submitStudentForm()">
                    <i class="bi bi-save"></i> 提交
                </button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const API_BASE = 'http://localhost:8088/api/students'; // 后端API地址
    let currentPage = 1;
    let itemsPerPage = 5;
    let totalPages = 1;
    let totalItems = 0;
    let selectedStudentId = null;
    let currentSearchTerm = '';

    // 页面加载时初始化
    $(document).ready(function() {
        loadStudents();
    });

    // 加载学生数据（带分页和搜索）
    function loadStudents(searchTerm = '', page = 1) {
        console.log(`加载学生数据，搜索词: "${searchTerm}"，页码: ${page}`);
        currentSearchTerm = searchTerm;
        currentPage = page;

        // 显示加载状态
        document.getElementById('student-table-body').innerHTML = `
            <tr>
                <td colspan="6" class="text-center">加载中...</td>
            </tr>
        `;

        let url = `${API_BASE}?_page=${page}&_limit=${itemsPerPage}`;
        if (searchTerm) {
            url += `&q=${encodeURIComponent(searchTerm)}`;
        }

        console.log(`请求URL: ${url}`);

        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                console.log('完整响应数据:', data);

                // 从后端返回的records字段获取数据列表
                const dataList = data.records || data;

                // 从后端返回的total字段获取总记录数
                totalItems = data.total !== undefined ? data.total : dataList.length;
                totalPages = Math.ceil(totalItems / itemsPerPage);

                renderStudents(dataList);
                updateSearchResultsInfo(searchTerm, totalItems);
                renderPagination();

                // 更新每页显示数量选择框
                document.getElementById('items-per-page').value = itemsPerPage;
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('获取数据失败 - 状态码:', jqXHR.status);
                console.error('错误信息:', errorThrown);
                console.error('响应文本:', jqXHR.responseText);

                document.getElementById('student-table-body').innerHTML = `
                    <tr>
                        <td colspan="6" class="text-center text-danger">获取数据失败: ${errorThrown}</td>
                    </tr>
                `;
                document.getElementById('search-results-info').textContent = '';
                renderPagination(); // 清空分页控件
            }
        });
    }

    // 渲染学生数据
    function renderStudents(students) {
        const tbody = document.getElementById('student-table-body');
        console.log('渲染数据列表长度:', students.length);

        if (students.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="6" class="text-center">没有找到学生数据</td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = students.map(s => `
            <tr>
                <td><input type="checkbox" class="student-checkbox" data-id="${s.studentNo}"></td>
                <td>${s.studentNo}</td>
                <td>${s.name}</td>
                <td>${s.gender}</td>
                <td>${s.birthday ? formatDate(s.birthday) : '-'}</td>
                <td class="action-buttons">
                    <button class="btn btn-sm btn-warning me-2" onclick="editStudent(${s.studentNo})">
                        <i class="bi bi-pencil"></i> 编辑
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="deleteStudent(${s.studentNo})">
                        <i class="bi bi-trash"></i> 删除
                    </button>
                </td>
            </tr>
        `).join('');

        // 绑定全选/取消全选事件
        document.getElementById('select-all').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    }

    // 渲染分页控件
    function renderPagination() {
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';

        // 如果没有数据或只有一页，不显示分页控件
        if (totalItems <= 0 || totalPages <= 1) {
            return;
        }

        // 添加上一页按钮
        const prevDisabled = currentPage === 1 ? 'disabled' : '';
        pagination.innerHTML += `
            <li class="page-item ${prevDisabled}">
                <button class="page-link" onclick="goToPage(${currentPage - 1})" aria-label="上一页">
                    <span aria-hidden="true">&laquo;</span>
                </button>
            </li>
        `;

        // 计算显示的页码范围
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        if (endPage - startPage < 4 && startPage > 1) {
            startPage = Math.max(1, endPage - 4);
        }

        // 添加页码按钮
        for (let i = startPage; i <= endPage; i++) {
            const active = i === currentPage ? 'active' : '';
            pagination.innerHTML += `
                <li class="page-item ${active}">
                    <button class="page-link" onclick="goToPage(${i})">${i}</button>
                </li>
            `;
        }

        // 添加下一页按钮
        const nextDisabled = currentPage === totalPages ? 'disabled' : '';
        pagination.innerHTML += `
            <li class="page-item ${nextDisabled}">
                <button class="page-link" onclick="goToPage(${currentPage + 1})" aria-label="下一页">
                    <span aria-hidden="true">&raquo;</span>
                </button>
            </li>
        `;
    }

    // 跳转到指定页面
    function goToPage(page) {
        if (page < 1 || page > totalPages) return;
        loadStudents(currentSearchTerm, page);
    }

    // 更改每页显示数量
    function changeItemsPerPage() {
        itemsPerPage = parseInt(document.getElementById('items-per-page').value);
        loadStudents(currentSearchTerm, 1); // 重置到第一页
    }

    // 日期格式化
    function formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return dateString; // 非标准格式直接显示

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // 更新搜索结果信息
    function updateSearchResultsInfo(searchTerm, totalItems) {
        const infoElement = document.getElementById('search-results-info');

        if (!searchTerm) {
            infoElement.textContent = '';
            return;
        }

        if (totalItems === 0) {
            infoElement.innerHTML = `
                <div class="alert alert-warning" role="alert">
                    <i class="bi bi-search"></i> 没有找到与 "${searchTerm}" 相关的学生记录
                </div>
            `;
        } else {
            infoElement.innerHTML = `
                <div class="alert alert-info" role="alert">
                    <i class="bi bi-search"></i> 找到 ${totalItems} 条与 "${searchTerm}" 相关的学生记录
                </div>
            `;
        }
    }

    // 搜索学生
    function searchStudents() {
        const searchTerm = document.getElementById('search-input').value.trim();
        loadStudents(searchTerm, 1); // 重置到第一页
    }

    // 重置搜索
    function resetSearch() {
        document.getElementById('search-input').value = '';
        loadStudents('');
    }

    // 支持按Enter键搜索
    document.getElementById('search-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchStudents();
        }
    });

    // 打开添加模态框
    function openAddModal() {
        selectedStudentId = null;
        document.getElementById('studentId').value = '';
        document.getElementById('student-form').reset();
        document.getElementById('birthday').value = ''; // 显式重置生日字段
        document.getElementById('student-modal-label').innerHTML = '<i class="bi bi-person-plus"></i> 添加学生';
        const modal = new bootstrap.Modal(document.getElementById('student-modal'));
        modal.show();
    }

    // 打开编辑模态框
    function editStudent(id) {
        $.ajax({
            url: `${API_BASE}/${id}`,
            method: 'GET',
            dataType: 'json',
            success: function(student) {
                console.log('编辑学生数据:', student);
                selectedStudentId = id;
                document.getElementById('studentId').value = student.studentNo;
                document.getElementById('name').value = student.name;
                document.getElementById('gender').value = student.gender;
                document.getElementById('birthday').value = student.birthday || ''; // 确保日期格式正确
                document.getElementById('student-modal-label').innerHTML = '<i class="bi bi-pencil"></i> 编辑学生';
                const modal = new bootstrap.Modal(document.getElementById('student-modal'));
                modal.show();
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('获取学生信息失败:', errorThrown);
                showAlert('获取学生信息失败: ' + errorThrown, 'danger');
            }
        });
    }

    // 编辑选中的学生
    function editSelectedStudent() {
        const checkedBoxes = document.querySelectorAll('.student-checkbox:checked');
        if (checkedBoxes.length === 0) {
            showAlert('请选择要编辑的学生', 'warning');
            return;
        }
        if (checkedBoxes.length > 1) {
            showAlert('一次只能编辑一个学生', 'warning');
            return;
        }
        const studentId = parseInt(checkedBoxes[0].dataset.id);
        editStudent(studentId);
    }

    // 删除选中的学生
    function deleteSelectedStudents() {
        const checkedBoxes = document.querySelectorAll('.student-checkbox:checked');
        if (checkedBoxes.length === 0) {
            showAlert('请选择要删除的学生', 'warning');
            return;
        }

        if (!confirm(`确定要删除选中的 ${checkedBoxes.length} 个学生吗？此操作不可撤销！`)) return;

        const studentIds = Array.from(checkedBoxes).map(checkbox => parseInt(checkbox.dataset.id));
        let successCount = 0;
        let errorCount = 0;

        function deleteNext() {
            if (studentIds.length === 0) {
                showAlert(`${successCount} 个学生删除成功${errorCount > 0 ? `，${errorCount} 个删除失败` : ''}`,
                    errorCount > 0 ? 'warning' : 'success');
                loadStudents(currentSearchTerm, currentPage); // 重新加载当前页
                return;
            }

            const studentId = studentIds.pop();
            $.ajax({
                url: `${API_BASE}/${studentId}`,
                method: 'DELETE',
                success: function() {
                    successCount++;
                    deleteNext();
                },
                error: function() {
                    errorCount++;
                    deleteNext();
                }
            });
        }

        deleteNext();
    }

    // 删除单个学生
    function deleteStudent(id) {
        if (!confirm('确定要删除该学生吗？此操作不可撤销！')) return;

        $.ajax({
            url: `${API_BASE}/${id}`,
            method: 'DELETE',
            success: function() {
                // 如果删除后当前页没有数据了，跳转到上一页
                if (totalItems - 1 <= (currentPage - 1) * itemsPerPage && currentPage > 1) {
                    loadStudents(currentSearchTerm, currentPage - 1);
                } else {
                    loadStudents(currentSearchTerm, currentPage);
                }
                showAlert('删除成功', 'success');
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('删除失败:', errorThrown);
                showAlert('删除失败: ' + errorThrown, 'danger');
            }
        });
    }

    // 提交学生表单（添加或更新）
    function submitStudentForm() {
        const id = selectedStudentId;
        const student = {
            name: document.getElementById('name').value.trim(),
            gender: document.getElementById('gender').value,
            birthday: document.getElementById('birthday').value
        };

        if (!student.name || !student.gender || !student.birthday) {
            showAlert('请填写所有必填字段', 'warning');
            return;
        }

        const method = id ? 'PUT' : 'POST';
        const url = id ? `${API_BASE}/${id}` : API_BASE;

        $.ajax({
            url: url,
            method: method,
            contentType: 'application/json',
            data: JSON.stringify(student),
            success: function() {
                loadStudents(currentSearchTerm, currentPage); // 重新加载当前页
                const modal = bootstrap.Modal.getInstance(document.getElementById('student-modal'));
                modal.hide();
                showAlert(id ? '更新成功' : '添加成功', 'success');
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('提交失败:', errorThrown);
                showAlert(id ? '更新失败: ' + errorThrown : '添加失败: ' + errorThrown, 'danger');
            }
        });
    }

    // 显示提示信息
    function showAlert(message, type) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 m-3`;
        alertDiv.style.zIndex = '9999';
        alertDiv.role = 'alert';
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;

        document.body.appendChild(alertDiv);

        // 3秒后自动关闭提示
        setTimeout(() => {
            alertDiv.classList.remove('show');
            setTimeout(() => alertDiv.remove(), 300);
        }, 3000);
    }
</script>
</body>
</html>